package com.young.rabbitmq.retry;

import com.rabbitmq.client.*;
import com.young.rabbitmq.util.ConnectionUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 消息生产者
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.buildConnection();
        Channel channel = connection.createChannel();
        // 消费失败的队列以及交换机
        channel.exchangeDeclare("fail_exchange", BuiltinExchangeType.DIRECT);
        channel.queueDeclare("fail_queue",true,false,false,null);
        channel.queueBind("fail_queue","fail_exchange","");

        // 重试队列，该队列设置了死信交换机，目的是在消息过期后将消息赚投到死信交换机，而这里的死信交换机绑定的就是上面的消费失败的交换机
        channel.exchangeDeclare("retry_exchange", BuiltinExchangeType.DIRECT);
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange","fail_exchange");
        channel.queueDeclare("retry_queue",true,false,false,map);
        channel.queueBind("retry_queue","retry_exchange","");


        // 达到最大重试次数后消息将会被转发到的死信队列
        channel.exchangeDeclare("dlx_exchange", BuiltinExchangeType.DIRECT);
        channel.queueDeclare("dlx_queue",true,false,false,null);
        channel.queueBind("dlx_queue","dlx_exchange","");


        // 在header 中设置重试次数，初始值为0
        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        Map<String,Object> header = new HashMap<>();
        header.put("retryCount",0);
        builder.headers(header);
        AMQP.BasicProperties basicProperties = builder.build();

        channel.basicPublish("fail_exchange","",basicProperties,"消息失败重试".getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();


    }
}
